

import 'dart:io';

import 'package:activity_record/model/data_base.dart';
import 'package:activity_record/model/diy.dart';
import 'package:activity_record/model/diy_image.dart';
import 'package:activity_record/model/diy_project.dart';
import 'package:activity_record/pages/diy_item_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:path_provider/path_provider.dart';
import 'package:transparent_image/transparent_image.dart';

class DiySearch extends StatefulWidget {
  // DiySearch({Key key, this.db}) : super(key: key);
  // var db;
  @override
  State<StatefulWidget> createState() => new DiySearchState();
}

class DiySearchState extends State<DiySearch> {
  final DataBase _database = new DataBase();
  String _text = '查错了不关我的事';
  //定义一个查询结果的数组
  List<Diy> _searchResult = [];
  List<DiyProject> _diyProjectResult = [];
  List<DiyImage> _imageDataResult = [];
  List _diyImages = [];
  TextEditingController _searchTextController = new TextEditingController();
  String _path = '';

  _getPath() async {
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
    await new Directory('${_directory.path}/image/')
        .create(recursive: true);
    _path = _imageDirectory.path;
    print('本次获得路径：${_imageDirectory.path}');
  }


  @override
  void initState() {
    _getPath();
  }

  //通过输入的字符串查询数据库
  _searchDiy(String value) async {
    var diyProjectresult = await _database.searchDiy(value);
    _searchResult = [];
    _diyProjectResult = [];
    _diyImages = [];
    if (diyProjectresult != null) {
      diyProjectresult.forEach((value) {
        _diyProjectResult.add(DiyProject.fromMap(value));
      });
      for (int i = 0; i < _diyProjectResult.length; i++) {
        _imageDataResult = [];
        var diyImageResult =
            await _database.getImageDatas(_diyProjectResult[i].id);
        diyImageResult.forEach((imageData) {
          _imageDataResult.add(DiyImage.fromMap(imageData,_path));
        });
        //将每个diy对应的所有图片数据添加到一个数组中
        _diyImages.add(_imageDataResult);
      }
      _text = '什么都没有查到';
    }
    setState(
      () {
        _searchResult = List.generate(_diyProjectResult.length, (index) {
          return new Diy(_diyProjectResult[index], _diyImages[index]);
        });
      },
    );
  }

  //进入活动卡片详情页面
  Future _enterDiyItem(Diy diy,int index) async {
    Navigator.of(context)
        .push(new MaterialPageRoute(builder: (BuildContext context) {
      return new DiyItemInfo(db: _database,diys: _searchResult,currentIndex: index,);
    }));
  }

  //每条查询结果的显示布局
  Widget _searchResultListTile(Diy diy,int index) {
    return new InkWell(
      onTap: () {
        print('taptap');
        _enterDiyItem(diy,index);
      },
      child: new Container(
        padding: const EdgeInsets.all(8.0),
        height: 100.0,
        child: new Row(
          children: <Widget>[
            new ClipRRect(
              borderRadius: BorderRadius.circular(4.0),
              child: new FadeInImage(
                placeholder: new MemoryImage(kTransparentImage),
                image: AssetImage(
                  diy.imageDatas.first.imageUrl,
                ),
                fit: BoxFit.cover,
                width: 100.0,
              ),
            ),
            new Expanded(
              flex: 2,
              child: new Container(
                margin: const EdgeInsets.only(left: 10.0),
                padding: const EdgeInsets.all(4.0),
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    new Text(
                      diy.diyProject.name,
                      style: new TextStyle(
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    new Text(diy.diyProject.contact),
                    new Row(
                      children: <Widget>[
                        new Text('${diy.diyProject.nums.toString()}元'),
                        new SizedBox(
                          width: 10.0,
                        ),
                        new Text('${diy.diyProject.singlePrcie.toString()}份')
                      ],
                    ),
                  ],
                ),
              ),
            ),
            new Container(
              padding: const EdgeInsets.all(4.0),
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  new Text(diy.diyProject.date),
                  new Text(diy.diyProject.place),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  //整个查询结果
  Widget _searchResultListView(List list) {
    return new Container(
      child: new ListView.builder(
        itemCount: _searchResult.length * 2,
        itemBuilder: (BuildContext context, index) {
          if (index.isOdd) {
            return new Divider(
              height: 0.0,
            );
          }
          index = index ~/ 2;
          return _searchResultListTile(list[index],index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new PreferredSize(
        preferredSize: Theme.of(context).platform == TargetPlatform.iOS
            ? new Size(0.0, 44.0)
            : new Size(0.0, 56.0),
        child: new AppBar(
          elevation:
              Theme.of(context).platform == TargetPlatform.iOS ? 1.0 : 4.0,
          //当leading或action为null的时候，title控件将会占据他们的空间
          automaticallyImplyLeading: false,
          title: _searchContainer(context),
          actions: <Widget>[
            new FlatButton(
              padding: const EdgeInsets.all(0.0),
              child: new Text(
                '取消',
                style: Theme.of(context)
                    .textTheme
                    .body1
                    .copyWith(color: Theme.of(context).scaffoldBackgroundColor),
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            )
          ],
        ),
      ),
      body: _searchResult.length == 0
          ? new Center(
              child: new Text(_text, style: new TextStyle(fontSize: 18.0)),
            )
          : _searchResultListView(_searchResult),
    );
  }

  //查询条件输入框封装
  Widget _searchContainer(BuildContext context) {
    return new Material(
      child: new Container(
        margin: const EdgeInsets.only(right: 10.0),
        padding: const EdgeInsets.fromLTRB(4.0, 4.0, 8.0, 4.0),
        alignment: Alignment.center,
        height: 30.0,
        decoration: new BoxDecoration(
            borderRadius: new BorderRadius.circular(12.0)),
        child: new Row(
          children: <Widget>[
            new Icon(
              Icons.search,
              color: Colors.grey[600],
            ),
            new Flexible(
              child: new TextField(
                textInputAction: TextInputAction.search,
                controller: _searchTextController,
                autofocus: true,
                decoration: InputDecoration.collapsed(
                    hintText: '活动名称、联系人',
                    hintStyle: Theme.of(context).textTheme.body1.copyWith(
                        color: Colors.grey[600], fontStyle: FontStyle.italic)),
                onChanged: (value) {
                  if (value != '') {
                    _searchDiy(value);
                  }
                  setState(() {
                    if (value == '') {
                      _searchResult.clear();
                    }
                  });
                },
              ),
            ),
            new InkWell(
              child: Container(
                  decoration: new BoxDecoration(
                      shape: BoxShape.circle, color: Colors.grey[400]),
                  child: new Icon(
                    Icons.clear,
                    color: Colors.white,
                    size: 19.0,
                  )),
              onTap: () {
                setState(() {
                  _searchTextController.clear();
                  _searchResult.clear();
                });
              },
            )
          ],
        ),
      ),
    );
  }
}
